<template>
  <div class="channelEdit">
    <van-cell>
      <div slot="title" class="title-text">我的频道</div>
      <!-- 编辑按钮 -->
      <van-button
        class="edit-btn"
        type="danger"
        plain
        round
        size="mini"
        @click="isEdit = !isEdit"
        >{{ isEdit ? "完成" : "编辑" }}</van-button
      >
    </van-cell>
    <van-grid :gutter="10">
      <van-grid-item
        class="grid-item"
        v-for="(channel, index) in myChannels"
        :key="index"
        @click="onMyChannelClick(channel, index)"
      >
        <van-icon
          v-show="isEdit && !fiexdChannels.includes(channel.id)"
          slot="icon"
          name="clear"
        ></van-icon>
        <span :class="{ active: index === active }" class="text" slot="text">{{
          channel.name
        }}</span>
      </van-grid-item>
    </van-grid>

    <!-- 频道推荐 -->
    <van-cell>
      <div slot="title" class="title-text">可添加频道</div>
    </van-cell>
    <van-grid :gutter="10">
      <van-grid-item
        class="grid-item"
        v-for="(channel, index) in recommendChannels"
        :key="index"
        :text="channel.name"
        @click="onAddChannel(channel)"
      />
    </van-grid>
  </div>
</template>

<script>
import { getAllChannelsAPI } from "@/api";
import { addUserChannelAPI } from "@/api";
import { deleteUserChannelAPI } from "@/api";
import { mapState } from "vuex";
import { setItem } from "@/utils/storage";

export default {
  props: {
    myChannels: {
      type: Array,
      required: true,
    },
    active: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      allChannels: [], //所有频道
      isEdit: false, //控制编辑状态的显示
      fiexdChannels: [0], //固定频道，不让删除
    };
  },
  computed: {
    ...mapState(["info"]),
    // 这段是简化版
    // 计算属性会观察内部依赖数据的变化
    // 如果依赖的数据发生变化，则计算属性会重新执行
    recommendChannels() {
      // 数组的filter方法：遍历数组，把符合条件的元素存到新数组中并返回
      return this.allChannels.filter((channel) => {
        // const channels []

        // 数组的find方法：遍历数组，把符合条件的第一个元素返回
        return !this.myChannels.find((myChannel) => {
          return myChannel.id === channel.id;
        });
      });
    },

    // recommendChannels(){
    //     const channels = []
    //     this.allChannels.forEach(channel => {
    //         // find遍历数组，找到满足条件的元素项
    //     const ret = this.myChannels.find(myChannel=>{
    //        return myChannel.id === channel.id
    //       })
    //     //   如果我的频道中不包括该频道，则收集该频道到推荐中
    //       if(!ret){
    //         channels.push(channel)
    //       }
    //     })
    //     // 把计算结果返回
    //     return channels
    // }
  },
  created() {
    this.loadAllChannels();
  },
  methods: {
    async loadAllChannels() {
      try {
        const { data } = await getAllChannelsAPI();
        this.allChannels = data.data.channels;
        console.log(data);
      } catch (err) {
        thid.$toast("数据获取失败");
      }
    },
    async onAddChannel (channel) {
      this.myChannels.push(channel);
      // 数据持久化
      if (this.user) {
        try {
          // 已登录，把数据请求接口放到线上
          await addUserChannelAPI({
            id: channel.id, //频道ID
            seq: this.myChannels.length, //序号
          });
        } catch (err) {
          this.$toast("保存失败，请稍后重试");
        }
      } else {
        // 未登录，把数据存储到本地
        setItem("HEADLINE_CHANNELS", this.myChannels);
      }
    },
    onMyChannelClick(channel, index) {
      if (this.isEdit) {
        //1 如果是固定频道则不删除
        if (this.fiexdChannels.includes(channel.id)) {
          return
        }
        // 2删除频道项
        this.myChannels.splice(index, 1);

        //  3 如果删除的激活频道之前的频道，则更新激活的频道项
        // 参数1：要删除的元素的开始索引（包括）
        // 参数2：删除的个数，如果不指定，则从参数1开始一直删除到最后
        if (index <= this.active) {
          // 让激活频道的索引-1
          this.$emit("update-active", this.active - 1, true);
        }

        // 4处理持久化
        this.deleteChannel(channel)
      } else {
        // 非编辑状态，执行切换频道
        this.$emit("update-active", index);
      }
    },

    async deleteChannel (channel){
     try {
       if (this.info) {
        // 已登录，将数据更新到线上
        await deleteUserChannelAPI(channel.id)
      }else{
        // 未登录，将数据更新到本地
        setItem('HEADLINE_CHANNELS',this.myChannels)
      }
     } catch (err) {
      this.$toast('操作失败，请稍后重试')
     }
    }
  },
};
</script>

<style scoped lang="less">
.channelEdit {
  padding: 85px 0;
  .title-text {
    font-size: 32px;
    color: #333333;
  }
  .edit-btn {
    width: 124px;
    height: 45px;
    font-size: 30px;
    color: #f85959;
    border: 1px solid #f85959;
  }

  /deep/ .grid-item {
    width: 160px;
    height: 86px;
    font-size: 36px;
    .van-icon-clear {
      position: absolute;
      right: -10px;
      top: -10px;
      font-size: 30px;
      color: #cacaca;
      z-index: 2;
    }
    .van-grid-item__content {
      white-space: nowrap;
      background: #f4f5f6;
      .van-grid-item__text,
      text {
        font-size: 30px;
        color: #222;
        margin-top: 0;
      }
      .active {
        color: red;
      }
      .van-grid-item__icon-wrapper {
        position: unset;
      }
    }
  }
}
</style>
